package com.qdxht.dispenser.utils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import com.qdxht.dispenser.service.MqttManagerService;
import com.qdxht.dispenser.service.MqttManagerService.MqttEventCallback;

import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import timber.log.Timber;

/**
 * MQTT工具类，提供对MQTT服务的简单访问
 */
public class MqttUtil {
    private static final String TAG = "MqttUtil";
    
    private static MqttManagerService mqttService;
    private static boolean serviceConnected = false;
    private static final Object serviceLock = new Object();
    
    private static ServiceConnection serviceConnection;
    
    /**
     * 初始化MQTT服务
     * @param context 上下文
     */
    public static void init(Context context,MqttEventCallback callback) {
        if (serviceConnection == null) {
            serviceConnection = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    Timber.tag(TAG).i("MQTT服务已绑定");
                    MqttManagerService.MqttBinder binder = (MqttManagerService.MqttBinder) service;
                    mqttService = binder.getService();
                    synchronized (serviceLock) {
                        serviceConnected = true;
                        serviceLock.notifyAll();
                        // 添加MQTT事件回调
                        addMqttEventCallback(callback);
                    }
                    boolean bl = connect();
                    Timber.tag(TAG).i("MQTT连接执行状态：%s", bl);
                    if(!bl){
                        connectFailure();
                    }
                }
                
                @Override
                public void onServiceDisconnected(ComponentName name) {
                    Timber.tag(TAG).w("MQTT服务已断开");
                    synchronized (serviceLock) {
                        mqttService = null;
                        serviceConnected = false;
                    }
                }
            };
        }
        
        // 启动并绑定服务
        Intent serviceIntent = new Intent(context, MqttManagerService.class);
        context.startService(serviceIntent);
        context.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    }
    
    /**
     * 释放MQTT服务
     * @param context 上下文
     */
    public static void release(Context context) {
        if (serviceConnection != null) {
            try {
                context.unbindService(serviceConnection);
            } catch (Exception e) {
                Timber.tag(TAG).e(e, "解绑MQTT服务出错");
            }
            serviceConnection = null;
        }
        // 清空回调
        if (mqttService != null) {
            mqttService.clearMqttEventCallback();
        }
        synchronized (serviceLock) {
            mqttService = null;
            serviceConnected = false;
        }
    }
    
    /**
     * 配置MQTT连接参数
     * @param serverUri 服务器地址
     * @param clientId 客户端ID
     * @param username 用户名
     * @param password 密码
     * @return 是否成功配置
     */
    public static boolean configureMqtt(String serverUri, String clientId, String username, String password) {
        if (ensureService()) {
            mqttService.configureMqtt(serverUri, clientId, username, password);
            return true;
        }
        return false;
    }
    
    /**
     * 连接到MQTT服务器
     * @return 是否成功发起连接请求
     */
    public static boolean connect() {
        if (ensureService()) {
            return mqttService.connectToMqttBroker();
        }
        return false;
    }
    
    /**
     * 断开MQTT连接
     */
    public static void disconnect() {
        if (ensureService()) {
            mqttService.disconnectMqtt();
        }
    }

    public static void connectFailure() {
        if (ensureService()) {
            mqttService.onConnectFailure();
        }
    }
    
    /**
     * 设置自动重连
     * @param autoReconnect 是否自动重连
     */
    public static void setAutoReconnect(boolean autoReconnect) {
        if (ensureService()) {
            mqttService.setAutoReconnect(autoReconnect);
        }
    }
    
    /**
     * 订阅主题
     * @param topic 主题名称
     * @param qos 服务质量 (0, 1, 2)
     * @return 是否成功发起订阅请求
     */
    public static boolean subscribe(String topic, int qos) {
        if (ensureService()) {
            return mqttService.subscribe(topic, qos);
        }
        return false;
    }
    
    /**
     * 订阅主题并设置消息监听器
     * @param topic 主题名称
     * @param qos 服务质量 (0, 1, 2)
     * @param messageListener 消息监听器
     * @return 是否成功发起订阅请求
     */
    public static boolean subscribe(String topic, int qos, IMqttMessageListener messageListener) {
        if (ensureService()) {
            return mqttService.subscribe(topic, qos, messageListener);
        }
        return false;
    }
    
    /**
     * 取消订阅主题
     * @param topic 主题名称
     * @return 是否成功发起取消订阅请求
     */
    public static boolean unsubscribe(String topic) {
        if (ensureService()) {
            return mqttService.unsubscribe(topic);
        }
        return false;
    }
    
    /**
     * 发布消息
     * @param topic 主题名称
     * @param payload 消息内容
     * @param qos 服务质量 (0, 1, 2)
     * @param retained 是否保留消息
     * @return 是否成功发起发布请求
     */
    public static boolean publish(String topic, String payload, int qos, boolean retained) {
        if (ensureService()) {
            Timber.tag(TAG).i( "publish：成功：" + topic + " " + payload);
            return mqttService.publish(topic, payload, qos, retained);
        }
        Timber.tag(TAG).i( "publish：失败：" + topic + " " + payload);
        return false;
    }
    
    /**
     * 检查是否已连接到MQTT服务器
     * @return 是否已连接
     */
    public static boolean isConnected() {
        if (ensureService()) {
            return mqttService.isConnected();
        }
        return false;
    }
    
    /**
     * 添加MQTT事件回调
     * @param callback 回调接口
     */
    public static void addMqttEventCallback(MqttEventCallback callback) {
        if (ensureService() && callback != null) {
            mqttService.addMqttEventCallback(callback);
        }
    }
    
    /**
     * 移除MQTT事件回调
     * @param callback 回调接口
     */
    public static void removeMqttEventCallback(MqttEventCallback callback) {
        if (ensureService() && callback != null) {
            mqttService.removeMqttEventCallback(callback);
        }
    }
    
    /**
     * 确保服务已连接
     * @return 服务是否可用
     */
    private static boolean ensureService() {
        synchronized (serviceLock) {
            if (!serviceConnected || mqttService == null) {
                Timber.tag(TAG).w("MQTT服务未连接");
                return false;
            }
            return true;
        }
    }
    
    /**
     * 创建一个简单的MQTT消息监听器
     * @param callback 回调接口
     * @return 消息监听器
     */
    public static IMqttMessageListener createMessageListener(final OnMessageArrivedListener callback) {
        return (topic, message) -> {
            if (callback != null) {
                String payload = new String(message.getPayload());
                callback.onMessageArrived(topic, payload, message);
            }
        };
    }
    
    /**
     * 消息到达监听接口
     */
    public interface OnMessageArrivedListener {
        /**
         * 当消息到达时调用
         * @param topic 主题
         * @param payload 消息内容（字符串形式）
         * @param message 原始MQTT消息对象
         */
        void onMessageArrived(String topic, String payload, MqttMessage message);
    }
} 